new Vue({
  el: '#app',
  data() {
    return {
      rules: {

      },
      form: {
        Delivery_SerialNumber: "",
        Store_SerialNumber: "",
        longitude: '',
        latitude: '',
        Enterprise_Info_SerialNumber: $.cookie('enterprise'),
        Children: {
          delivery_detail: [{
            Delivery_Detail_SerialNumber: '',
            Delivery_SerialNumber: '',
            Delivery_Distance: '',
            Delivery_Amount: '',
            Sales_Amount: ''
          }]
        }
      },
      tabsname: [],
      loading: false,
      isUrl: false,
      map: null, // 存储地图实例
      markerLayer: null, // 存储标记图层
      address: '',
      value1: true,
      value2: true
    }
  },
  methods: {

    tabname() {
      const _this = this;
      $.ajax({
        url: `${DomainName}/getInquiryAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          Data: 'store_info',
        },
        success: function (res) {
          _this.tabsname = res.filter(item => item.Enterprise_Info_SerialNumber == _this.form.Enterprise_Info_SerialNumber);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    new_xt() {
      const _this = this
      $.ajax({
        url: DomainName + "/getSubtableInquiryOriginal?token=" + $.cookie("token"),
        data: {
          Primary_Key: sessionStorage.getItem("Delivery_SerialNumber"),
          JSONObject: JSON.stringify({ delivery_info: { delivery_detail: {} } })
        },
        type: "POST",
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        success: function (res) {
          console.log(res);
          _this.form = res.delivery_info[0];
          _this.getMap(_this.form.longitude, _this.form.latitude);
          _this.getLocation();
        }
        ,
        dataType: "json"
      });

    },
    handleSwitchChange() {
      if (this.value2) {
        this.change3D();
      } else {
        this.change2D();
      }
    },
    getStore_Address() {
      // 获取选中店铺的值
      const selectedStore = this.tabsname.find(item => item.Store_SerialNumber === this.form.Store_SerialNumber);
      // 将店铺地址赋给地址输入框
      if (selectedStore) {
        this.address = selectedStore.Store_Address;
        this.getAddress();
      }
    },
    getAddress() {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getAddressResolutionAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          Address: this.address,
        },
        success: function (res) {
          console.log(res);
          _this.form.longitude = res.Data.lng;
          _this.form.latitude = res.Data.lat;
          let position = new TMap.LatLng(_this.form.latitude, _this.form.longitude);
          // 移动地图中心到指定位置
          _this.map.setCenter(position);
          let marker = null;

          _this.map.on("click", (evt) => {
            // 清除之前的标点
            if (marker) {
              marker.setMap(null);
            }
            // 添加新的标点
            marker = new TMap.MultiMarker({
              map: _this.map,
              geometries: [{
                position: evt.latLng,
              }]
            });
    
            _this.form.longitude = evt.latLng.getLng().toFixed(6);
            _this.form.latitude = evt.latLng.getLat().toFixed(6);
            _this.getLocation();
            // 移动地图中心到新标点位置
            _this.map.setCenter(evt.latLng);
          });
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getLocation() {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getLocationResolutionAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          latitude: this.form.latitude,
          longitude: this.form.longitude,
        },
        success: function (res) {
          console.log(res);
          _this.address = res.Data.address + res.Data.formatted_addresses.recommend;
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getEnterprise(callback) {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getEnterpriseLocationAction?token=${$.cookie('token')}`,
        type: 'GET',
        success: function (res) {
          console.log(res);
          // _this.form.longitude = res.Data.longitude;
          // _this.form.latitude = res.Data.latitude;
          callback(res.Data.longitude, res.Data.latitude);
          console.log('a',res.Data.longitude, res.Data.latitude);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getMap(longitude, latitude) {
      this.map = new TMap.Map("container", {
        center: new TMap.LatLng(latitude, longitude),
        zoom: 17,
        pitch: 45, //设置俯仰角度（0~45）,
        viewMode: '3D',
      });
      this.markerLayer = new TMap.MultiMarker({
        map: this.map
      });
      let marker = null;

      this.map.on("click", (evt) => {
        // 清除之前的标点
        if (marker) {
          marker.setMap(null);
        }
        // 添加新的标点
        marker = new TMap.MultiMarker({
          map: this.map,
          geometries: [{
            position: evt.latLng,
          }]
        });

        this.form.longitude = evt.latLng.getLng().toFixed(6);
        this.form.latitude = evt.latLng.getLat().toFixed(6);
        this.getLocation();
        // 移动地图中心到新标点位置
        this.map.setCenter(evt.latLng);
      });
    },
    change2D() {
      this.map.setViewMode('2D');
    },
    change3D() {
      this.map.setViewMode('3D');
      this.map.setPitch(70);
    },
    submitForm() {
      const _this = this;
      this.$refs['contract'].validate((valid) => {
        if (valid) {
          _this.loading = true
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { delivery_info: [modify] } }) }
          } else {
            data = { Data: JSON.stringify({ Modify: { delivery_info: [modify] }, Add: { delivery_info: [add], } }), }
          }
          console.log(JSON.parse(data.Data));
          $.ajax({
            url: `${DomainName}/getEditAction?token=${$.cookie('token')}`,
            type: 'POST',
            data,
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.history.go(-1);
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        }
      })
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_delivery_detail = [], modify_delivery_detail = []

      for (const i in modify.Children.delivery_detail) {
        const obj = modify.Children.delivery_detail[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_delivery_detail.push(obj)
        } else {
          modify_delivery_detail.push(obj)
        }
      }

      add.Children.delivery_detail = add_delivery_detail
      modify.Children.delivery_detail = modify_delivery_detail

      if (add_delivery_detail.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    add_system_model_mark() {
      this.form.Children.delivery_detail.push({
        Delivery_Detail_SerialNumber: '',
        Delivery_SerialNumber: this.form.Delivery_SerialNumber,
        Delivery_Distance: '',
        Delivery_Amount: '',
        Sales_Amount: ''
      })
      console.log(this.form);
    },
    remove_system_model_mark() {
      if (this.form.Children.delivery_detail.filter(item => item.Row_Status != '1').length > 1) {
        let i = this.form.Children.delivery_detail.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.delivery_detail.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.delivery_detail.pop()
        } else {
          this.$confirm('警告！此操作将删除一条权限标识,可能会引起页面问题, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.delivery_detail.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
  },
  mounted() {
    this.new_xt()
    this.tabname()
    //加载地图
    // this.getEnterprise((longitude, latitude) => {
      // this.getMap(longitude, latitude)
    // });
  }
})